<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <view class="page-container">
    <view class="content">
      <view class="bg-white px-4 py-3">
        <view class="text-sm text-gray-600">客户：{{ extUser.name }}</view>
      </view>

      <view class="bg-white mt-2 px-4 py-3 flex items-center justify-between">
        <view class="flex items-center">
          <image :src="extUser.avatar" class="w-10 h-10 shrink-0" mode="scaleToFill" />
          <view class="ml-3">
            <view class="text-base font-medium">郑州国际新城二期(6号院)</view>
            <view class="text-sm text-gray-500">1号楼/1单元/第03层/1-1-301</view>
            <view class="text-xs text-gray-400 mt-1">杜（家属）</view>
          </view>
        </view>
        <view>
          <wd-button :round="false" size="small">切换</wd-button>
        </view>
      </view>
      <view class="font-100 text-sm p-4 bg-white text-right">
        支持录音识别或者选择聊天记录进行智能识别
      </view>
      <view class="flex items-center justify-between bg-white">
        <view>
          <view class="px-4 pt-3 pb-1">
            <view v-if="chat" class="max-w-[90%] bg-[#4477ee] p-3 rounded-lg rounded-tl-none">
              <p class="text-sm text-white">
                {{ chat }}
              </p>
            </view>
          </view>
          <view class="flex items-center px-4 bg-white">
            <span class="text-xs text-gray-400">{{ chatTime }}</span>
          </view>
        </view>
        <view>
          <image
            class="w-16 h-8"
            src="/static/svg/mic.svg"
            mode="scaleToFill"
            @touchstart="handleMic"
            @touchend="handleMicEnd"
          />
        </view>
      </view>

      <view class="flex justify-between bg-white px-4 py-3">
        <view>
          <wd-button :round="false" type="info" icon="history" size="small" @click="handleHistory">
            聊天记录
          </wd-button>
        </view>
        <view>
          <wd-button :round="false" type="info" icon="delete" size="small" @click="handleEmpty">
            清空
          </wd-button>
        </view>
        <view>
          <wd-button :round="false" size="small" @click="handleAgent">智能识别</wd-button>
        </view>
      </view>

      <view class="bg-white mt-2 px-4 py-3 pb-18">
        <view class="mt-4 p-4 bg-[#E8EDFF] rounded-lg">
          <view class="flex items-center mb-2">
            <image class="w-4 h-4 mr-2" src="/static/svg/jiqiren.svg" mode="scaleToFill" />
            <span class="text-sm text-[#4477ee] font-medium">AI 智能回复建议</span>
          </view>
          <wd-textarea
            v-model="recommendContent"
            :maxlength="225"
            readonly
            size="large"
            placeholder="请输入..."
            auto-height
            style="--wot-textarea-bg: #e8edff; --wot-textarea-not-empty-border-color: #e8edff"
          />
        </view>
        <view class="text-right">
          <wd-button @click="show = true" plain class="mt-3" :round="false" size="small">
            修改话术
          </wd-button>
        </view>
      </view>
      <wd-popup
        v-model="show"
        position="bottom"
        lock-scroll
        :close-on-click-modal="false"
        closable
        :safe-area-inset-bottom="true"
        custom-style="height: 500px;"
      >
        <view class="p-[12px] bg-gray-100 h-[500px]">
          <view class="font-medium mb-2">修改话术：</view>
          <wd-textarea
            class="mt-3"
            v-model="recommendContent"
            :maxlength="225"
            clearable
            show-word-limit
            size="large"
            placeholder="请输入..."
            custom-textarea-class="textarea-content"
          />
        </view>
      </wd-popup>
      <wd-popup
        v-model="showHistory"
        position="right"
        lock-scroll
        :close-on-click-modal="false"
        closable
        :safe-area-inset-bottom="true"
      >
        <view class="p-10 min-w-[70vw]">
          <view v-for="(item, index) in chatList" :key="index">
            <view class="flex items-start mb-4" v-if="item.flag == '2'">
              <img :src="item.avatar" class="w-10 h-10 rounded-full mr-2" />
              <view class="max-w-[90%]">
                <view class="text-sm text-gray-600 mb-1">{{ item.name }}</view>
                <view
                  class="bg-white px-4 py-2 rounded-lg text-sm inline-block"
                  @click="handleChoose(item)"
                >
                  {{ item.content }}
                </view>
                <view class="text-xs text-gray-400 mt-1">{{ item.msgtime }}</view>
              </view>
            </view>
          </view>
        </view>
      </wd-popup>
      <view class="fixed py-3 bottom-0 w-full bg-white border-t border-gray-100 z-9999">
        <button
          @click="handleSendChatMessage"
          class="w-80 m-auto bg-#4477ee text-white font-medium !rounded-b"
        >
          发送
        </button>
      </view>
    </view>
    <wd-toast />
  </view>
</template>

<script lang="ts" setup>
//
import { getInfo, getChatDataList, IChat, getOwnerWechatInfo } from './api'
import * as ww from '@wecom/jssdk'
import { registerWeChat } from '@/utils/wecom'
import { useToast } from 'wot-design-uni'
import { Icon } from '@uni-helper/uni-types/index'
registerWeChat()
const toast = useToast()
const recommendContent = ref('')
const show = ref(false)
const showHistory = ref(false)
onShow(() => {
  getChatData()
})
const chatList = ref<IChat[]>([])
const chat = ref('上门保洁的是你们物业自己的员工吗，还是和第三方合作的，售后问题找谁啊')
const chatTime = ref('10:25')
function handleEmpty() {
  chat.value = ''
  chatTime.value = ''
}
const extUser = ref<{ name?: string; avatar?: string }>({ name: '', avatar: '' })
function getChatData() {
  // 获取外部联系人 id
  ww.getCurExternalContact({
    success: (res: any) => {
      console.log(res)
      const externalUserid = res.userId
      getOwnerWechatInfo({ external_userid: externalUserid }).then((res2) => {
        extUser.value = res2.data
      })
      getInfo().then((res3) => {
        console.log(res3)
        const butlerId = res3.user.userId

        getChatDataList({ butlerId, externalUserid }).then((res4: IResData<IChat[]>) => {
          const shorterSender = findShortestSender(res4.rows)
          chatList.value = res4.rows.map((item) => {
            const sender = item.sender
            const senderName = shorterSender === sender ? '管家' : '业主'
            const contentObj = JSON.parse(item.content)
            return {
              ...item,
              senderName,
              content: contentObj.content,
            }
          })
        })
      })
    },
  })
}
onBeforeUnmount(() => {
  ww.stopRecord({
    success: (res: any) => {
      console.log(res, 'stop-record')
    },
  })
  timer && clearTimeout(timer)
})
let startTime, endTime, timer
const localId = ref('') // 存储录音本地ID
const micFlag = ref(false)
function handleMic() {
  startTime = Date.now()
  micFlag.value = true
  timer = setTimeout(() => {
    ww.startRecord({
      success: (res: any) => {
        console.log(res, 'start-record')
        // updateDuration()
      },
      cancel(res) {
        console.log('取消录音')
      },
    })
  }, 300)
}
function handleMicEnd() {
  clearTimeout(timer)
  micFlag.value = false
  endTime = Date.now()
  const duration = Math.floor((endTime - startTime) / 1000)
  if (duration < 3) {
    toast.error({
      msg: '录音时间不能少于3秒',
      duration: 1000,
    })
    return
  }
  toast.loading({
    msg: '正在转码...',
  })
  ww.stopRecord({
    success: (res: any) => {
      localId.value = res.localId
      ww.translateVoice({
        localId: localId.value,
        success: (res: any) => {
          console.log(res, 'translateVoice')
          chat.value = res.translateResult
        },
      })
    },
    fail(res) {
      console.log('录音失败')
    },
  })
}
function handleChoose(obj: IChat) {
  chat.value = obj.content
  chatTime.value = obj.msgtime
}
function findShortestSender(messages) {
  let shortestSender = null // 初始化为 null，表示尚未找到
  let minLength = Infinity // 初始化为无穷大，以便任何长度都会比它小

  for (let i = 0; i < messages.length; i++) {
    const sender = messages[i].sender
    const length = sender.length

    if (length < minLength) {
      minLength = length
      shortestSender = sender
    }
  }

  return shortestSender
}
const handleSendChatMessage = () => {
  ww.sendChatMessage({
    msgtype: 'text',
    text: {
      content: recommendContent.value,
    },
    fail: (res: any) => {
      console.log('发送消息失败', res)
    },
  })
}
function handleHistory() {
  showHistory.value = true
}
function handleAgent() {
  toast.loading({
    msg: '识别中...',
    duration: 1000,
    closed: () => {
      recommendContent.value = `亲爱的业主您好，我很理解您的顾虑。我们的保洁团队全部都是物业公司自己培训和管理的专业人员，不是外包服务。每位保洁阿姨都经过严格筛选和岗前培训，持证上岗。如果服务过程中有任何问题，您可以： 1. 直接向现场保洁人员反馈 2. 拨打物业服务热线 3.通过APP提交售后工单 我们承诺24小时内响应处理，让您住得省心、舒心！`
    },
  })
}
</script>

<style lang="scss" scoped>
//
.page-container {
  min-height: calc(100vh - 44px);
  background-color: #f5f7fa;
}

:deep(.textarea-content) {
  height: 500rpx;
}
</style>
